import { createReducer, createActions } from 'reduxsauce'
import Immutable from 'seamless-immutable'

/* ------------- Types and Action Creators ------------- */

const { Types, Creators } = createActions({
  orderRequest: ['token', 'code'],
  orderSuccess: ['itemList'],
  orderFailure: null,
})

export const OrderTypes = Types
export default Creators

/* ------------- Initial State ------------- */

export const INITIAL_STATE = Immutable({
  code: null,
  itemList: null,
  payload: {normal:null,finished:null,refund:null},
  fetching: null,
  error: null
})

/* ------------- Reducers ------------- */

// request the data from an api
export const request = (state, {token, code}) =>
  state.merge({ fetching: true, error:null, code })

// successful api lookup
export const success = (state, action) => {
  const { itemList } = action
  return state.merge({
    fetching: false,
    error: null,
    payload: {...state.payload, [state.code]:itemList},
    code: null,
  })
}

// Something went wrong somewhere.
export const failure = state =>
  state.merge({ fetching: false, error: true, code:null })

/* ------------- Hookup Reducers To Types ------------- */

export const reducer = createReducer(INITIAL_STATE, {
  [Types.ORDER_REQUEST]: request,
  [Types.ORDER_SUCCESS]: success,
  [Types.ORDER_FAILURE]: failure,
})
